//
//  ZGSHomeController.m
//  MapleLeaf
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "ZGSHomeController.h"
#import "ZGSScrollCell.h"
#import "ZGSTypeListViewController.h"
#import "ZGSHomeReusableView.h"
#import "ZGSHomeHeaderModel.h"
#import "ZGSHomeCartoonModel.h"
#import "ZGSScroller.h"
#import <UIImageView+WebCache.h>
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "BaseAFN.h"
#import "ZGSMoreCartoonViewController.h"
#import "ZGSCartoonDetailsViewController.h"
#import "ZGSBookShelfViewController.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ZGSHomeController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate>
@property (nonatomic, retain) NSMutableArray *scrollArr;
@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) NSMutableArray *homeArr;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UIPageControl *page;
@property (nonatomic, retain) UITextField *searchTextField;
@property (nonatomic, retain) MBProgressHUD *hud;


@end

@implementation ZGSHomeController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    覆盖UINavigationControllerHead
    UIView *naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    naviView.backgroundColor = [UIColor colorWithRed:0.961f green:0.325f blue:0.173f alpha:1.00f];
    [self.view addSubview:naviView];
    
    UIImageView *headImageView = [[UIImageView alloc] init];
    headImageView.frame = CGRectMake(10 * WIDTH / 375.0, 15, WIDTH / 4, 44);
    headImageView.image = [UIImage imageNamed:@"headImage.png"];
    [naviView addSubview:headImageView];
    //
    
    //轮播图(用collection的方法)
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((WIDTH - 40) / 3.0 - 2, HEIGHT * 0.3);
    flowLayout.minimumInteritemSpacing = 10 * WIDTH / 375.0;
    flowLayout.minimumLineSpacing = 10 * HEIGHT / 667.0;
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * HEIGHT / 667.0, 10 * WIDTH / 375.0, 0, 10 * WIDTH / 375.0);
    flowLayout.headerReferenceSize = CGSizeMake(WIDTH, 35);
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    self.collectionView.bounces = NO;
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.collectionView registerClass:[ZGSHomeReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CRReuse"];
    [self.collectionView registerClass:[ZGSScrollCell class] forCellWithReuseIdentifier:@"HCReuse"];
    
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.contentInset = UIEdgeInsetsMake(HEIGHT / 4.0, 0, 0, 0);
 

    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changePicAction) userInfo:nil repeats:YES];
    self.navigationController.hidesBottomBarWhenPushed = YES;
    
    
    
    //搜索栏(textField)
    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(WIDTH / 4 + 20, 28, WIDTH / 4 * 3 - 70, 28)];
    self.searchTextField.backgroundColor = [UIColor whiteColor];
    self.searchTextField.placeholder = @"搜漫画";
    self.searchTextField.textAlignment = NSTextAlignmentCenter;

    [naviView addSubview:self.searchTextField];
    
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    historyButton.frame = CGRectMake(WIDTH - 40 / 375.0 * WIDTH, 27, 30 / 375.0 * WIDTH, 30 / 375.0 * WIDTH);
    [historyButton setBackgroundImage:[UIImage imageNamed:@"iconfont-lishicheliang.png"] forState:UIControlStateNormal];
    [historyButton addTarget:self action:@selector(lookHistoryAction:) forControlEvents:UIControlEventTouchUpInside];
    [naviView addSubview:historyButton];

    self.searchTextField.delegate = self;
    
    
    
    
    [self getData];

//
    
    

       
}


#pragma mark - scrollView Method

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        
        if (self.scrollView.contentOffset.x == (self.scrollArr.count + 1) * WIDTH) {
            self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        }
        else if (self.scrollView.contentOffset.x == 0)
            self.scrollView.contentOffset = CGPointMake(self.scrollArr.count * WIDTH, 0);
    }
    self.page.currentPage = self.scrollView.contentOffset.x / WIDTH - 1;
}

- (void)changePicAction {
    if (self.scrollView.contentOffset.x == WIDTH * (self.scrollArr.count)) {
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        self.page.currentPage = 0;
    }
    else {
        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x + WIDTH, 0);
        self.page.currentPage++;
    }
}

#pragma mark - textFieldDelegate
//点击搜索的方法
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    ZGSTypeListViewController *typeListVC = [[ZGSTypeListViewController alloc] init];
    typeListVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:typeListVC animated:YES];
    [textField resignFirstResponder];

}


#pragma mark -get & saveData
- (void)getData {
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"Cartoon/home.plist"];
    
    NSLog(@"%@", docPath);
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
    NSMutableArray *arr = dic[@"data"][@"columns"];
    self.homeArr = [NSMutableArray array];
    self.homeArr = [ZGSHomeHeaderModel baseModelByArr:arr];
    NSInteger i = 0;
    for (ZGSHomeHeaderModel *tempHeader in self.homeArr) {
        tempHeader.cartoonArr = [NSMutableArray array];
        tempHeader.cartoonArr = [ZGSHomeCartoonModel baseModelByArr:arr[i][@"contents"]];
        i++;
    }
    NSMutableArray *scrollArr = dic[@"data"][@"sliders"];
    self.scrollArr = [NSMutableArray array];
    self.scrollArr = [ZGSScroller baseModelByArr:scrollArr];
    if (self.scrollArr.count > 1) {
        [self createSrollViewAndPageView];
        [self.collectionView reloadData];
//        判断
        AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
        [netManager startMonitoring];
        [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            
            switch (status) {
                case -1:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络提示" message:@"当前网络未知" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                }
                case 0:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                }
                case 1:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络提示" message:@"当前网络为移动网" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                }
                case 2:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络提示" message:@"当前网络为wlan" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                }
                    
                default:
                    break;
            }
            
            if (status == -1 || status == 0) {
                [self.hud removeFromSuperview];
                
                MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:hud];
                hud.mode = MBProgressHUDModeText;
                hud.yOffset = - 245 * HEIGHT / 667.0;
                hud.margin = 10.0;
                hud.labelText = @"数据请求失败,请检查网络后重试";
                [hud showAnimated:YES whileExecutingBlock:^{
                    sleep(2);
                } completionBlock:^{
                    [hud removeFromSuperview];
                
                }];
            } else {
                
                [self createData];
            }
            
        }];
        [netManager stopMonitoring];
        
    }
    else {
        
        // 网络判断
        AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
        [netManager startMonitoring];
        [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            
            if (status == -1 || status == 0) {
                [self.hud removeFromSuperview];
                
                MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:hud];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"数据请求失败,请检查网络后重试";
                [hud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [hud removeFromSuperview];
     
                }];
            } else {
                self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                self.hud.labelText = @"加载中…";
                
                [self createData];
            }
            
        }];
        [netManager stopMonitoring];
    }

    [self createData];
}
- (void)createSrollViewAndPageView {
    
    if (!_scrollView) {
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, - HEIGHT / 4, WIDTH, HEIGHT / 4)];
        self.scrollView.contentSize = CGSizeMake((self.scrollArr.count + 2) * WIDTH, 0);
        self.scrollView.pagingEnabled = YES;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        
        self.scrollView.userInteractionEnabled = YES;
        
        // 添加点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollAction:)];
        [self.scrollView addGestureRecognizer:tap];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        
        UIImageView *firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4)];
        [firstImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr.lastObject pic]] placeholderImage:[UIImage imageNamed:@"backWhite.png"]];
        [self.scrollView addSubview:firstImageView];
        
        UILabel *firstBgLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT / 4 - 20, WIDTH, 20)];
        firstBgLabel.backgroundColor = [UIColor colorWithRed:0.961f green:0.325f blue:0.173f alpha:1.00f];
        firstBgLabel.alpha = 0.7;
        [firstImageView addSubview:firstBgLabel];

        
        UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, HEIGHT / 4 - 20, WIDTH / 3 * 2, 20)];
        firstLabel.text = [self.scrollArr.lastObject title];
        firstLabel.textColor = [UIColor whiteColor];
        firstLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        [firstImageView addSubview:firstLabel];
        
        for (NSInteger i = 0; i < self.scrollArr.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * (i + 1), 0, WIDTH, HEIGHT / 4)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr[i] pic]] placeholderImage:[UIImage imageNamed:@"backWhite.png"]];
            [self.scrollView addSubview:imageView];

            UILabel *bgLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT / 4 - 20, WIDTH, 20)];
            bgLabel.backgroundColor = [UIColor colorWithRed:0.961f green:0.325f blue:0.173f alpha:1.00f];
            bgLabel.alpha = 0.7;
            [imageView addSubview:bgLabel];

            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, HEIGHT / 4 - 20, WIDTH / 3 * 2, 20)];
            label.text = [self.scrollArr[i] title];
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
            [imageView addSubview:label];

        }
        
        UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.scrollArr.count + 1) * WIDTH, 0, WIDTH, HEIGHT / 4)];
        [lastImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr.firstObject pic]] placeholderImage:[UIImage imageNamed:@"backWhite.png"]];
        [self.scrollView addSubview:lastImageView];
        
        UILabel *lastBgLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT / 4 - 20, WIDTH, 20)];
        lastBgLabel.backgroundColor = [UIColor colorWithRed:0.961f green:0.325f blue:0.173f alpha:1.00f];
        lastBgLabel.alpha = 0.7;
        [lastImageView addSubview:lastBgLabel];
        
        UILabel *lastLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, HEIGHT / 4 - 20, WIDTH / 3 * 2, 20)];
        lastLabel.text = [self.scrollArr.firstObject title];
        lastLabel.textColor = [UIColor whiteColor];
        lastLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        [lastImageView addSubview:lastLabel];

        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        [self.collectionView addSubview:self.scrollView];
        
        self.scrollView.delegate = self;
    }
    // 创建pageControl
    if (!_page) {
        self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH - 60, -20 , 60, 20)];
        self.page.numberOfPages = self.scrollArr.count;
        self.page.currentPageIndicatorTintColor = [UIColor whiteColor];
        [self.collectionView addSubview:self.page];

        
        [self.page addTarget:self action:@selector(changePageAction:) forControlEvents:UIControlEventValueChanged];

    }
}


#pragma mark - creatData
- (void)changePageAction:(UIPageControl *)page {
    [self.scrollView setContentOffset:CGPointMake((page.currentPage + 1) * WIDTH, 0) animated:YES];
}
- (void)createData {
    [BaseAFN GETURLByString:@"http://api.youqudao.com/mhapi/api/recommend?customerId=1913463&uuid=64:b4:73:28:fd:2c&market=20&appversion=21" AFNData:^(id result) {
        NSMutableArray *arr = result[@"data"][@"columns"];
        self.homeArr = [NSMutableArray array];
        self.homeArr = [ZGSHomeHeaderModel baseModelByArr:arr];
        NSInteger i = 0;
        for (ZGSHomeHeaderModel *tempHeader in self.homeArr) {
            tempHeader.cartoonArr = [NSMutableArray array];
            tempHeader.cartoonArr = [ZGSHomeCartoonModel baseModelByArr:arr[i][@"contents"]];
            i++;
        }
        NSMutableArray *scrollArr = result[@"data"][@"sliders"];
        self.scrollArr = [NSMutableArray array];
        self.scrollArr = [ZGSScroller baseModelByArr:scrollArr];
        NSLog(@"1");
        
        if (self.scrollArr.count > 1) {
            [self createSrollViewAndPageView];
        }
        
        if (self.hud) {
            [self.hud removeFromSuperview];
            
        }
        
        [self.collectionView reloadData];
        [self saveData:result];

    }];
  
}


- (void)saveData:(id)object {
  
//    NSString *sandBoxPath1 = [NSSearchPathForDirectoriesInDomains(<#NSSearchPathDirectory directory#>, <#NSSearchPathDomainMask domainMask#>, <#BOOL expandTilde#>)]
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *cacheFile = [sandBoxPath stringByAppendingPathComponent:@"Cartoon"];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // 判断是否存在文件夹
    if (![manager fileExistsAtPath:cacheFile]) {
        [manager createDirectoryAtPath:cacheFile withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"Cartoon/home.plist"];
    NSDictionary *dic = object;
    // 归档(存数据)
    [NSKeyedArchiver archiveRootObject:dic toFile:docPath];
    
}

#pragma mark - collectionDelegate & DateSource


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.homeArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 3;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGSScrollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HCReuse" forIndexPath:indexPath];
    
    ZGSHomeCartoonModel *cartoon = [self.homeArr[indexPath.section] cartoonArr][indexPath.row];
    // 链接转UTF8设置图片
    NSString * encodingString = [cartoon.pic stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [cell.picView sd_setImageWithURL:[NSURL URLWithString:encodingString] placeholderImage:[UIImage imageNamed:@"backgroundImage.png"]];
    
    cell.titleLabel.text = cartoon.name;
    cell.numberLabel.text = [NSString stringWithFormat:@"更新到%@集", cartoon.updateSize];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    //对collection就行赋值
    if (kind == UICollectionElementKindSectionHeader) {
        ZGSHomeReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CRReuse" forIndexPath:indexPath];
        reusableView.typeLabel.text = [self.homeArr[indexPath.section] name];
        reusableView.button.tag = 100 + indexPath.section;
        [reusableView.button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        
        return reusableView;
    }
    
    
    return nil;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGSCartoonDetailsViewController *catoonDetailVC = [[ZGSCartoonDetailsViewController alloc] init];
    
    ZGSHomeCartoonModel *cartoon = [self.homeArr[indexPath.section] cartoonArr][indexPath.row];
    catoonDetailVC.albumId = cartoon.targetId;
    catoonDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:catoonDetailVC animated:YES];
    
    
}



#pragma mark - ButtonMethod

- (void)click:(UIButton *)button {
    ZGSMoreCartoonViewController *moreVC = [[ZGSMoreCartoonViewController alloc] init];
    moreVC.header = self.homeArr[button.tag - 100];
    
    moreVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:moreVC animated:YES];
   }
//查看搜索历史记录
- (void)lookHistoryAction:(UIButton *)button {
    ZGSBookShelfViewController *bcVC = [[ZGSBookShelfViewController alloc] init];
    bcVC.isShowHeadImage = YES;
    [self.navigationController pushViewController:bcVC animated:YES];

  
    
 
}

#pragma mark - tapScrollAction


// scrollView点击事件
- (void)tapScrollAction:(UITapGestureRecognizer *)tap {
    UIScrollView *scrollView = (UIScrollView *)tap.view;
    NSInteger i = scrollView.contentOffset.x / WIDTH;
    if ([[self.scrollArr[i - 1] albumId] integerValue] > 0) {
        ZGSCartoonDetailsViewController *cdVC = [[ZGSCartoonDetailsViewController alloc] init];
        cdVC.albumId = [self.scrollArr[i - 1] albumId];
        [self.navigationController pushViewController:cdVC animated:YES];
    }

    
    

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
//    printf(@"0 -> 1 -> 4 -> 2 -> 5 -> 8 -> 3 -> 6 -> 9 -> 7 -> 10 -> 11")
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
